﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Adalbertus.BudgetPlanner.Domain;
using Adalbertus.BudgetPlanner.Domain.Repositories;
using NHibernate.Linq;

namespace Adalbertus.BudgetPlanner.Infrastructure.Repositories
{
    public class Repository<TDomain> : IRepository<TDomain>
    {
        public IUnitOfWork UnitOfWork { get; private set; }

        public Repository(IUnitOfWork unitOfWork)
        {
            Contract.Requires<ArgumentNullException>(unitOfWork != null);
            UnitOfWork = unitOfWork;
        }

        public virtual void Save(TDomain domain)
        {
            UnitOfWork.Session.SaveOrUpdate(domain);
        }

        public void Save(IEnumerable<TDomain> domains)
        {
            foreach (TDomain domain in domains)
            {
                Save(domain);
            }
        }

        public virtual void Remove(TDomain domain)
        {
            UnitOfWork.Session.Delete(domain);
        }

        public virtual TDomain GetById(int id)
        {
            return UnitOfWork.Session.Get<TDomain>(id);
        }

        public virtual IEnumerable<TDomain> GetAll()
        {
            return UnitOfWork.Session.Query<TDomain>().ToList();
        }
    }
}
